﻿using Microsoft.Web.Administration;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.ServiceProcess;
using System.Threading;
using System.Windows.Forms;

namespace Leaf.NetCore.HotUpdate
{
    public partial class IISMain : Form
    {
        public IISMain()
        {
            InitializeComponent();
        }

        public static int editState = 0; //1新增 2编辑
        public static IISXmlModel editModel = null; //修改实体
        public static List<Dictionary<string, string>> iisList = null; //iis列表
        public static List<IISXmlModel> getIISCfg = null; //配置列表
        public static string[] excludeList = null; //修改实体
        public static Dictionary<string, FileSystemWatcher> watcherDict = null; //文件监控
        public static Dictionary<string, Thread> threadDict = null; //线程
        public static Dictionary<string, ManualResetEvent> eventDict = null; //线程内部控制
        public static Dictionary<string, int> secondDict = null; //时间
        public static List<FileInfoModel> fileList = null;
        public static string defaultExclude = ".zip;.config;.cache;runtimes;UpImg;appsettings.json;log4net.xml;LeafAjax.js;DapperService.js;DateDirective.js;";

        private void Form1_Load(object sender, EventArgs e)
        {
            //IISNTest();
            //cmb_iisList.SelectedText = cmb_iisList.Items[0].ToString();
            if (ExistSqlServerService("W3SVC"))
            {
                AddLog("【验证程序】验证IIS已存在");
                txt_exclude.Text = defaultExclude;
                PubListInit();
                IISCfgInit();
                AutoPubWeb();
            }
            else
            {
                grb_main.Enabled = false;
                AddLog("【验证程序】验证IIS不存在");
            }
        }

        #region 公共方法

        public delegate void SetLstCallback(string message);

        /// <summary>
        /// 信息显示
        /// </summary>
        /// <param name="txt"></param>
        public void AddLogAsyn(string txt)
        {
            if (this.lst_note.InvokeRequired)
            {
                SetLstCallback d = new SetLstCallback(AddLogAsyn);
                this.Invoke(d, new object[] { txt });
            }
            else
            {
                //Log4Helper.Write(txt);
                txt = DateTime.Now.ToString("MM-dd HH:mm:ss") + "：" + txt;
                if (lst_note.Items.Count > 100)
                {
                    lst_note.Items.Clear();
                }
                lst_note.Items.Insert(0, txt);
            }
        }

        public void AddLog(string txt)
        {
            //Log4Helper.Write(txt);
            txt = DateTime.Now.ToString("MM-dd HH:mm:ss") + "：" + txt;
            if (lst_note.Items.Count > 100)
            {
                lst_note.Items.Clear();
            }
            lst_note.Items.Insert(0, txt);
        }

        private static string progress = "0";
        private static int progIndex = 0;
        private static int printCount = 0; //文件总个数
        private static int excludeCount = 0; //过滤文件个数

        /// <summary>
        /// 文件夹下所有内容copy
        /// </summary>
        /// <param name="SourcePath">要Copy的文件夹</param>
        /// <param name="DestinationPath">要复制到哪个地方</param>
        /// <param name="overwriteexisting">是否覆盖</param>
        /// <returns></returns>
        private static bool CopyDirectory(string SourcePath, string DestinationPath, string[] exclude = null, Loading pLoading = null)
        {
            bool ret = false;
            try
            {
                //string SourcePath = editModel.ftppath;
                //string DestinationPath = editModel.iispath;
                SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\";
                DestinationPath = DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\";

                if (Directory.Exists(SourcePath))
                {
                    if (Directory.Exists(DestinationPath) == false && DestinationPath.Contains("backup") == false)
                    {
                        Directory.CreateDirectory(DestinationPath);
                    }

                    var getFiles = Directory.GetFiles(SourcePath);
                    printCount = printCount + getFiles.Length;

                    foreach (string fls in getFiles)
                    {
                        FileInfo flinfo = new FileInfo(fls);
                        if (exclude.Contains(flinfo.Name) || exclude.Contains(flinfo.Extension))
                        {
                            //progIndex++;
                            printCount--;
                            excludeCount++;
                            progress = ((progIndex * 100) / printCount).ToString();
                            if (pLoading != null)
                            {
                                pLoading.SetCaptionAndDescription($"执行进度 {progIndex} / " + printCount, progress);
                            }

                            continue;
                        }
                        flinfo.CopyTo(DestinationPath + flinfo.Name, true);
                        progIndex++;
                        progress = ((progIndex * 100) / printCount).ToString();
                        if (pLoading != null)
                        {
                            pLoading.SetCaptionAndDescription($"执行进度 {progIndex} / " + printCount, progress);
                        }
                    }
                    foreach (string drs in Directory.GetDirectories(SourcePath))
                    {
                        DirectoryInfo drinfo = new DirectoryInfo(drs);
                        if (CopyDirectory(drs, DestinationPath + drinfo.Name, exclude, pLoading) == false)
                            ret = false;
                    }
                }
                ret = true;
                //DirectoryInfo di = new DirectoryInfo(SourcePath);
                //di.Delete(true);
            }
            catch (Exception ex)
            {
                ret = false;
            }
            finally
            {
            }
            return ret;
        }

        /// <summary>
        /// 判断IIS服务
        /// </summary>
        /// <param name="tem"></param>
        /// <returns></returns>
        public static bool ExistSqlServerService(string tem)
        {
            bool ExistFlag = false;
            ServiceController[] service = ServiceController.GetServices();
            for (int i = 0; i < service.Length; i++)
            {
                if (service[i].ServiceName.ToString() == tem)
                {
                    ExistFlag = true;
                }
            }
            return ExistFlag;
        }

        #endregion 公共方法

        #region IIS配置文件

        /// <summary>
        /// 初始化发布信息
        /// </summary>
        /// <param name="name"></param>
        public void PubListInit(string name = "")
        {
            cmb_pubList.Items.Clear();
            getIISCfg = IISXmlBLL.GetModelListFromCache();
            foreach (var item in getIISCfg)
            {
                cmb_pubList.Items.Add(item.name);
            }
            string pubName = "";
            if (name == "")
            {
                pubName = System.Configuration.ConfigurationManager.AppSettings["PubName"];
            }
            else
            {
                pubName = name;
            }

            if (pubName != "")
            {
                int isPub = cmb_pubList.Items.IndexOf(pubName);
                if (isPub != -1)
                {
                    cmb_pubList.SelectedIndex = isPub;
                    foreach (var item in getIISCfg)
                    {
                        if (item.name != pubName)
                        {
                            continue;
                        }
                        lbl_iisName.Text = item.iisname;
                        lbl_iisPath.Text = item.iispath;
                        lbl_ftpPath.Text = item.ftppath;
                        lbl_exclude.Text = "排除文件：" + item.exclude;
                        editModel = item;
                        break;
                    }
                }
                else
                {
                    cmb_pubList.SelectedIndex = 0;
                    editModel = getIISCfg[0];
                }
            }
            else
            {
                cmb_pubList.SelectedIndex = 0;
                editModel = getIISCfg[0];
            }
            lbl_iisName.Text = editModel.iisname;
            lbl_iisPath.Text = editModel.iispath;
            lbl_ftpPath.Text = editModel.ftppath;
            txt_sec.Text = editModel.second;
            if (editModel.watcher == "1")
            {
                btn_watcher.Enabled = false;
                txt_sec.Enabled = false;
                btn_watcherStop.Enabled = true;
            }
            else
            {
                btn_watcher.Enabled = true;
                txt_sec.Enabled = true;
                btn_watcherStop.Enabled = false;
            }
            lbl_exclude.Text = "排除文件：" + editModel.exclude;
            CmbBackUpInit();
        }

        /// <summary>
        /// 初始化备份文件列表
        /// </summary>
        public void CmbBackUpInit()
        {
            fileList = DirFileHelper.GetAllFileName(editModel.ftppath + "\\backup");
            cmb_backup.Items.Clear();
            if (fileList == null || fileList.Count == 0) return;
            fileList = fileList.OrderByDescending(p => p.FileModify).ToList();
            if (fileList != null && fileList.Count > 0)
            {
                foreach (var folder in fileList)
                {
                    cmb_backup.Items.Add(folder.FileName);
                }
                cmb_backup.SelectedIndex = 0;
            }
        }

        public string[] GetExcludeList(IISXmlModel model)
        {
            string[] result = model.exclude.Split(';');
            return result;
        }

        public IISXmlModel GetIISCfgModelByName(string name)
        {
            return getIISCfg.Where(x => x.name == name).FirstOrDefault();
        }

        public IISXmlModel GetIISCfgModelByPath(string name)
        {
            return getIISCfg.Where(x => x.ftppath == name).FirstOrDefault();
        }

        /// <summary>
        /// 监控文件变化发布程序
        /// </summary>
        public void AutoPubWeb()
        {
            watcherDict = new Dictionary<string, FileSystemWatcher>();
            threadDict = new Dictionary<string, Thread>();
            eventDict = new Dictionary<string, ManualResetEvent>();
            secondDict = new Dictionary<string, int>();
            foreach (var item in getIISCfg)
            {
                if (item.watcher == "1")
                {
                    var watcher = new FileSystemWatcher(item.ftppath);
                    watcher.Created += Watcher_Changed;
                    watcher.Changed += Watcher_Changed;
                    watcher.EnableRaisingEvents = true;
                    watcherDict.Add(item.name, watcher);
                    Thread thread = new Thread(ThdCopyFile);
                    threadDict.Add(item.name, thread);
                    ManualResetEvent _event = new ManualResetEvent(false);
                    eventDict[item.name] = _event;
                    thread.Start(item);
                    secondDict.Add(item.name, int.Parse(item.second));
                    AddLog(item.name + "-文件监控开启");
                }
            }
        }

        #endregion IIS配置文件

        #region IIS相关操作

        public bool StopIISWeb(string name)
        {
            ServerManager server = new ServerManager();

            SiteCollection sites = server.Sites;
            var getWeb = sites.Where(p => p.Name == name).FirstOrDefault();
            if (getWeb.State.ToString() == "Started")
            {
                getWeb.Stop();
            }
            return true;
        }

        public bool GetWebState(string name)
        {
            ServerManager server = new ServerManager();
            SiteCollection sites = server.Sites;
            var getWeb = sites.Where(p => p.Name == name).FirstOrDefault();
            if (getWeb.State.ToString() == "Started")
            {
                return true;
            }
            return false;
        }

        public bool StartIISWeb(string name)
        {
            ServerManager server = new ServerManager();
            SiteCollection sites = server.Sites;
            var getWeb = sites.Where(p => p.Name == name).FirstOrDefault();
            if (getWeb.State.ToString() != "Started")
            {
                getWeb.Start();
            }
            return true;
        }

        public void IISCfgInit()
        {
            cmb_iisList.Items.Clear();
            iisList = GetIISList();
            foreach (var item in iisList)
            {
                cmb_iisList.Items.Add(item["name"]);
            }
            cmb_iisList.SelectedIndex = 0;
        }

        public static List<Dictionary<string, string>> GetIISList()
        {
            List<Dictionary<string, string>> result = new List<Dictionary<string, string>>();
            Dictionary<string, string> resultItem = null;
            ServerManager server = new ServerManager();
            SiteCollection sites = server.Sites;

            foreach (Site site in sites)
            {
                resultItem = new Dictionary<string, string>();
                resultItem.Add("name", site.Name);
                resultItem.Add("path", site.Applications["/"].VirtualDirectories["/"].PhysicalPath);
                resultItem.Add("state", site.State.ToString() == "Started" ? "已启用" : "已停止");
                resultItem.Add("bind", site.Bindings[0].BindingInformation);
                result.Add(resultItem);
            }
            return result;
        }

        public Dictionary<string, string> GetIISModel(string name)
        {
            Dictionary<string, string> result = null;
            foreach (var item in iisList)
            {
                if (item["name"] != name)
                {
                    continue;
                }
                result = item;
                break;
            }
            return result;
        }

        #endregion IIS相关操作

        private void CopyFile()
        {
            Loading pLoading = Loading.getLoading();
            excludeList = GetExcludeList(editModel);
            KillProcCore(editModel.iisname);
            //StopIISWeb(editModel.iisname);
            AddLogAsyn("【进程关闭】" + editModel.iisname);
            //Thread.Sleep(1000);
            AddLogAsyn("【文档复制】" + "复制中...");
            CopyDirectory(editModel.ftppath, editModel.iispath, excludeList, pLoading);
            AddLogAsyn("【复制结束】" + "复制文件：" + printCount + ".过滤文件：" + excludeCount);
            ZipBackupFile(editModel);
            //StartIISWeb(editModel.iisname);
            //AddLogAsyn("【网站开启】" + editModel.iisname);
            Loading.getLoading().CloseLoadingForm();
        }

        //private delegate void ThdCopyFile(IISXmlModel model);

        /// <summary>
        /// 发布web
        /// </summary>
        /// <param name="model"></param>
        private void ThdCopyFile(object obj)
        {
            IISXmlModel model = obj as IISXmlModel;
            while (true)
            {
                eventDict[model.name].WaitOne();
                if (secondDict[model.name] > 0)
                {
                    secondDict[model.name] = secondDict[model.name] - 1;
                    //AddLogAsyn(model.name + "倒计时：" + secondDict[model.name]);
                    Thread.Sleep(1000);
                }
                else
                {
                    excludeList = GetExcludeList(model);
                    KillProcCore(model.iisname);
                    //StopIISWeb(editModel.iisname);
                    AddLogAsyn("【进程关闭】" + model.iisname);
                    //Thread.Sleep(1000);
                    AddLogAsyn("【文档复制】" + "复制中...");
                    progress = "0";
                    progIndex = 0;
                    printCount = 0;
                    excludeCount = 0;
                    CopyDirectory(model.ftppath, model.iispath, excludeList);
                    AddLogAsyn("【复制结束】" + "复制文件：" + printCount + ".过滤文件：" + excludeCount);
                    ZipBackupFile(model);
                    eventDict[model.name].Reset();
                }
            }

            //StartIISWeb(editModel.iisname);
            //AddLogAsyn("【网站开启】" + editModel.iisname);
        }

        /// <summary>
        /// 网站备份
        /// </summary>
        /// <param name="model"></param>
        private void ZipBackupFile(IISXmlModel model)
        {
            return;
            ZipHelper zipHelper = new ZipHelper();
            string saveName = "[" + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + "]" + model.name + ".zip";
            Directory.CreateDirectory(model.ftppath + "\\backup\\");
            excludeList = GetExcludeList(model);
            zipHelper.CreatZipDir(model.iispath, model.ftppath + "\\backup\\" + saveName, excludeList);
            ClearZipBackup(model);
        }

        /// <summary>
        /// 清理备份文件，当天的留15份，其他天数留最新一个，一共留15个
        /// </summary>
        /// <param name="model"></param>
        private void ClearZipBackup(IISXmlModel model)
        {
            var getBackup = DirFileHelper.GetAllFileName(model.ftppath + "\\backup");
            if (getBackup == null || getBackup.Count == 0)
            {
                return;
            }
            getBackup = getBackup.OrderByDescending(p => p.FileModify).ToList();
            var dateOne = getBackup[0].FileModify;
            var dateEnd = getBackup[getBackup.Count - 1].FileModify;
            var dateNow = DateTime.Now.ToString("yyyy-MM-dd");
            var groupList = getBackup.GroupBy(p => p.FileModify.ToString("yyyy-MM-dd")).ToList();
            List<FileInfoModel> modelItem = null;
            for (int i = 0; i < groupList.Count; i++)
            {
                modelItem = groupList[i].ToList();
                if (i > 15)
                {
                    for (int j = 0; j < modelItem.Count; j++)
                    {
                        File.Delete(modelItem[j].FilePath);
                    }
                }
                else
                {
                    if (groupList[i].Key == dateNow)
                    {
                        if (modelItem.Count > 15)
                        {
                            for (int j = 15; j < modelItem.Count; j++)
                            {
                                File.Delete(modelItem[j].FilePath);
                            }
                        }
                    }
                    else
                    {
                        for (int j = 1; j < modelItem.Count; j++)
                        {
                            File.Delete(modelItem[j].FilePath);
                        }
                    }
                }
            }
        }

        private void btn_pub_Click(object sender, EventArgs e)
        {
            progress = "0";
            progIndex = 0;
            printCount = 0;
            excludeCount = 0;
            Loading pLoading = Loading.getLoading();
            pLoading.SetExecuteMethod(CopyFile);
            pLoading.ShowDialog();
            //excludeList = GetExcludeList();
            //StopIISWeb(editModel.iisname);
            //AddLog(editModel.iisname + "-已停止");
            //AddLog("文档复制中...");
            //CopyDirectory(editModel.ftppath, editModel.iispath);
            //AddLog("文档复制完毕");
            //StartIISWeb(editModel.iisname);
            //AddLog(editModel.iisname + "-已启动");
        }

        private void btn_edit_Click(object sender, EventArgs e)
        {
            editState = 2;
            grb_edit.Text = "编辑区-编辑状态";
            grb_edit.Enabled = true;
            txt_name.Text = editModel.name;
            lbl_selFtp.Text = editModel.ftppath;
            txt_exclude.Text = editModel.exclude;
            int isIIS = cmb_iisList.Items.IndexOf(editModel.iisname);
            Dictionary<string, string> getIISModel = null;
            if (isIIS != -1)
            {
                cmb_iisList.SelectedIndex = isIIS;
                getIISModel = GetIISModel(editModel.iisname);
            }
            else
            {
                cmb_iisList.SelectedIndex = 0;
                getIISModel = GetIISModel(cmb_iisList.Text);
            }
            lbl_iisInfo.Text = string.Format("IIS信息：\n站点名称：{0} \n当前状态：{1} \n站点路径：{2} \n绑定信息：{3}", getIISModel["name"], getIISModel["state"], getIISModel["path"], getIISModel["bind"]);
        }

        private void btn_add_Click(object sender, EventArgs e)
        {
            txt_name.Text = "";
            lbl_selFtp.Text = "选择文件夹名称";
            txt_exclude.Text = defaultExclude;
            editState = 1;
            grb_edit.Text = "编辑区-新增状态";
            grb_edit.Enabled = true;
        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            if (editState == 1) //新增
            {
                var oldModel = GetIISCfgModelByName(txt_name.Text);
                if (oldModel != null)
                {
                    AddLog(txt_name.Text + "-已存在");
                    MessageBox.Show(txt_name.Text + "-已存在");
                    return;
                }
                if (lbl_ftpPath.Text == "选择ftp上传文件夹")
                {
                    MessageBox.Show("请选择ftp上传文件夹");
                    return;
                }
                IISXmlModel model = new IISXmlModel();
                editModel.name = txt_name.Text;
                editModel.iisname = cmb_iisList.Text;
                var getIISModel = GetIISModel(cmb_iisList.Text);
                editModel.iispath = getIISModel["path"];
                editModel.ftppath = lbl_selFtp.Text;
                editModel.exclude = txt_exclude.Text;
                editModel.pubdate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                editModel.second = "20";
                editModel.watcher = "0";
                var result = IISXmlBLL.AddItem(editModel, (getIISCfg.Count + 1).ToString());
                if (result)
                {
                    AddLog(txt_name.Text + "-新增成功");
                    MessageBox.Show("新增成功");
                }
                else
                {
                    AddLog(txt_name.Text + "-新增失败");
                    MessageBox.Show("新增失败");
                }
                grb_edit.Text = "编辑区";
                grb_edit.Enabled = false;
                txt_sec.Enabled = true;
                btn_watcher.Enabled = true;
                btn_watcherStop.Enabled = false;
                PubListInit(txt_name.Text);
            }
            else //修改
            {
                if (editModel.name != txt_name.Text)
                {
                    var oldModel = GetIISCfgModelByName(txt_name.Text);
                    if (oldModel != null)
                    {
                        AddLog(txt_name.Text + "-已存在");
                        MessageBox.Show(txt_name.Text + "-已存在");
                        return;
                    }
                }
                editModel.name = txt_name.Text;
                editModel.iisname = cmb_iisList.Text;
                var getIISModel = GetIISModel(cmb_iisList.Text);
                editModel.iispath = getIISModel["path"];
                editModel.ftppath = lbl_selFtp.Text;
                editModel.exclude = txt_exclude.Text;
                editModel.pubdate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                var result = IISXmlBLL.EditItem(editModel);
                if (result)
                {
                    AddLog(txt_name.Text + "-修改成功");
                    MessageBox.Show("修改成功");
                }
                else
                {
                    AddLog(txt_name.Text + "-修改失败");
                    MessageBox.Show("修改失败");
                }
                grb_edit.Text = "编辑区";
                grb_edit.Enabled = false;
                PubListInit(txt_name.Text);
            }
        }

        private void cmb_pubList_SelectedIndexChanged(object sender, EventArgs e)
        {
            var oldModel = GetIISCfgModelByName(cmb_pubList.Text);
            editModel = oldModel;
            lbl_iisName.Text = editModel.iisname;
            lbl_iisPath.Text = editModel.iispath;
            lbl_ftpPath.Text = editModel.ftppath;
            lbl_exclude.Text = "排除文件：" + editModel.exclude;
            txt_sec.Text = editModel.second;
            if (editModel.watcher == "1")
            {
                btn_watcher.Enabled = false;
                txt_sec.Enabled = false;
                btn_watcherStop.Enabled = true;
            }
            else
            {
                btn_watcher.Enabled = true;
                txt_sec.Enabled = true;
                btn_watcherStop.Enabled = false;
            }
            CmbBackUpInit();
        }

        private void btn_selFtp_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog path = new FolderBrowserDialog();
            path.ShowDialog();
            lbl_selFtp.Text = path.SelectedPath;
        }

        private void cmb_iisList_SelectedIndexChanged(object sender, EventArgs e)
        {
            Dictionary<string, string> getIISModel = null;
            getIISModel = GetIISModel(cmb_iisList.Text);
            lbl_iisInfo.Text = string.Format("IIS信息：\n站点名称：{0} \n当前状态：{1} \n站点路径：{2} \n绑定信息：{3}", getIISModel["name"], getIISModel["state"], getIISModel["path"], getIISModel["bind"]);
        }

        private void btn_reIIS_Click(object sender, EventArgs e)
        {
            IISCfgInit();
        }

        private void btn_webStart_Click(object sender, EventArgs e)
        {
            StartIISWeb(editModel.iisname);
        }

        private void btn_webStop_Click(object sender, EventArgs e)
        {
            StopIISWeb(editModel.iisname);
        }

        private void btn_test_Click(object sender, EventArgs e)
        {
            //ClearZipBackup(editModel);

            //string[] excludeExt = new string[] { "test", "567" };
            //var test = excludeExt.Contains("test1234");
            //AddLog(test.ToString());
            //ZipHelper zipHelper = new ZipHelper();
            //string saveName = "[" + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + "]" + editModel.name + ".zip";
            //Directory.CreateDirectory(editModel.ftppath + "\\backup\\");
            //string[] excludeExt = new string[] { ".pdb" };
            //string[] excludeDir = new string[] { "runtimes" };
            //string[] excludeFile = null;
            //zipHelper.CreatZipDir(editModel.iispath, editModel.ftppath + "\\backup\\" + saveName, excludeExt, excludeDir, excludeFile);
        }

        private void KillProcCore(string name)
        {
            var main = Process.GetProcesses();
            foreach (Process vProc in main)   //[BugHere]:请不要加.Exe后缀名称
            {
                if (vProc.ProcessName.ToLower() == "w3wp") //Process.GetCurrentProcess
                {
                    var procName = GetProcessUserName(vProc.Id);
                    if (procName == name)
                    {
                        vProc.Kill();
                        KillProcCore(procName);
                        break;
                    }
                }
            }
        }

        private static string GetProcessUserName(int pID)
        {
            string userName = string.Empty;

            try
            {
                foreach (ManagementObject item in new ManagementObjectSearcher("Select * from Win32_Process WHERE processID=" + pID).Get())
                {
                    ManagementBaseObject inPar = null;
                    ManagementBaseObject outPar = null;

                    inPar = item.GetMethodParameters("GetOwner");
                    outPar = item.InvokeMethod("GetOwner", inPar, null);

                    userName = Convert.ToString(outPar["User"]);

                    break;
                }
            }
            catch
            {
                userName = "SYSTEM";
            }

            return userName;
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.ShowInTaskbar = true;
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.Activate();
        }

        private void IISMain_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.ShowInTaskbar = false;
                this.Visible = false;
                notifyIcon1.Visible = true;
            }
        }

        private void Main_ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.ShowInTaskbar = true;
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.Activate();
        }

        private void Exit_ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
        }

        #region 监控发布

        private void txt_sec_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 0x20) e.KeyChar = (char)0;  //禁止空格键
            if ((e.KeyChar == 0x2D) && (((TextBox)sender).Text.Length == 0)) return;   //处理负数
            if (e.KeyChar > 0x20)
            {
                try
                {
                    double.Parse(((TextBox)sender).Text + e.KeyChar.ToString());
                }
                catch
                {
                    e.KeyChar = (char)0;   //处理非法字符
                }
            }
        }

        private void btn_watcher_Click(object sender, EventArgs e)
        {
            txt_sec.Enabled = false;
            btn_watcher.Enabled = false;
            btn_watcherStop.Enabled = true;
            if (watcherDict.ContainsKey(editModel.name))
            {
                watcherDict[editModel.name].EnableRaisingEvents = true;
            }
            else
            {
                var watcher = new FileSystemWatcher(editModel.ftppath);
                watcher.Created += Watcher_Changed;
                watcher.Changed += Watcher_Changed;
                watcher.EnableRaisingEvents = true;
                watcherDict.Add(editModel.name, watcher);
            }

            editModel.second = txt_sec.Text;
            editModel.watcher = "1";
            var result = IISXmlBLL.EditItem(editModel);
            if (result)
            {
                AddLog(editModel.name + "-监控发布开启成功");
                //MessageBox.Show("修改成功");
            }
            else
            {
                AddLog(editModel.name + "-监控发布开启失败");
                //MessageBox.Show("修改失败");
            }
        }

        private void Watcher_Changed(object sender, FileSystemEventArgs e)
        {
            if (e.Name == "backup")
            {
                return;
            }
            var thisWatcher = sender as FileSystemWatcher;
            var getModel = GetIISCfgModelByPath(thisWatcher.Path);
            secondDict[getModel.name] = int.Parse(getModel.second);
            eventDict[getModel.name].Set();
            //if (eventDict[getModel.name].WaitOne() == false)
            //{
            //    eventDict[getModel.name].Set();
            //}

            //AddLogAsyn(editModel.ftppath + "|" + String.Format("{0}:{1}:{2}", getModel.name, e.ChangeType, e.Name));
        }

        private void btn_watcherStop_Click(object sender, EventArgs e)
        {
            //editModel.second = txt_sec.Text;
            txt_sec.Enabled = true;
            btn_watcher.Enabled = true;
            btn_watcherStop.Enabled = false;
            editModel.watcher = "0";
            var result = IISXmlBLL.EditItem(editModel);
            if (result)
            {
                watcherDict[editModel.name].EnableRaisingEvents = false;
                AddLog(editModel.name + "-监控发布停止");

                //MessageBox.Show("修改成功");
            }
            else
            {
                AddLog(editModel.name + "-监控发布停止失败");
                //MessageBox.Show("修改失败");
            }
        }

        #endregion 监控发布

        private void btn_recover_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(cmb_backup.Text) == false)
            {
                var nowModel = fileList.Where(p => p.FileName == cmb_backup.Text).FirstOrDefault();
                ZipHelper.UnZip(nowModel.FilePath, editModel.iispath);
                AddLog(editModel.name + "已还原：" + cmb_backup.Text);
            }
            else
            {
                MessageBox.Show("无还原文件", "提醒");
            }
        }

        private void IISMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            System.Environment.Exit(0);
        }
    }
}